package br.com.jbssistemas.loterica.filtros;

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author daniel
 *
 */
@WebFilter(filterName = "AuthFilter", urlPatterns = {"/*"})
public class AuthFilter implements Filter {

    private static final boolean debug = true;

    private FilterConfig filterConfig = null;

    public AuthFilter() {
    }

    /**
     *
     * @param request The servlet request we are processing
     * @param response The servlet response we are creating
     * @param chain The filter chain we are processing
     *
     * @exception IOException if an input/output error occurs
     * @exception ServletException if a servlet error occurs
     */
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest rq = (HttpServletRequest) request;

        HttpServletResponse rp = (HttpServletResponse) response;

        Object object = rq.getSession().getAttribute("loged");

        Boolean loged = false;

        if (object != null) {

            loged = (Boolean) object;

        }

        String url = rq.getRequestURL().toString();

        if (loged == false) {

            if (!url.endsWith("/loteria-sao-francisco/index.jsf") && !url.endsWith(".css")
                    && !url.endsWith(".js") && !url.endsWith(".jpg")
                    && !url.endsWith(".gif") && !url.contains("javax.faces.resource")
                    && !url.contains(".png") && !url.contains("Acesso")
                    && !url.contains("Erro") && !url.contains("404")) {

                rp.sendRedirect("/loteria-sao-francisco/index.jsf");

            }

        }

        try {

            chain.doFilter(request, response);

        } catch (Throwable t) {

            System.err.println(t);

        }

    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }

}
